<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>7-1鼠标约束</title>
</head>
<body>
<div id="c"></div>

<script src="../js/matter.js"></script>
<script>
  let Engine = Matter.Engine // 引擎.引擎模块包含创建和操作引擎的方法
  let Render = Matter.Render // 基于HTML5画布的渲染器
  let Bodies = Matter.Bodies // 用于创建各种形状的物体，物体必须添加到Wolrd中，然后由引擎运行世界
  let Composite = Matter.Composite // 复合体，旧版的 Matter.World 已经合并到这个模块里
  let Runner = Matter.Runner // 循环模块
  let Mouse = Matter.Mouse
  let MouseConstraint = Matter.MouseConstraint

  // 创建引擎
  let engine = Engine.create()

  // 创建渲染器
  let render = Render.create({
    element: document.getElementById('c'), // 绑定页面元素,
    engine: engine,
    options: {
      width: 400,
      height: 400,
      wireframes: false, // 关闭线框模式
      showVelocity: true // 显示速度
    }
  })

  // 矩形A
  let rect = Bodies.rectangle(80, 100, 80, 80, {
    restitution: 0.3,
    mass: 0.1
  })

  // 地面
  let ground = Bodies.rectangle(200, 390, 400, 20, {
    isStatic: true,
    render: {
      fillStyle: '#cccccc'
    }
  })

  // 创建鼠标实例
  let mouse = Mouse.create(render.canvas)
  
  // 给鼠标添加约束
  let mouseConstraint = MouseConstraint.create(engine, {
    mouse: mouse,
    constraint: {
      stiffness: 0.2,
      render: {
        visible: false // 默认为 true，会显示鼠标拖拽轨迹
      }
    }
  })

  // 将鼠标约束添加到物理引擎中
  Composite.add(engine.world, [rect, ground, mouseConstraint])

  Render.run(render)

  // 创建运行方法
  let runner = Runner.create()

  // 运行渲染器
  Runner.run(runner, engine)
</script>
</body>
</html>